<template>
  <div class="user-list-page">
    <div class="handle-box">
      <el-button
        type="primary"
        class="add-user-button"
        icon="Plus"
        @click="userAddDialog = true"
        >新增员工</el-button
      >

      <el-button
        type="primary"
        class="batch-add-user-button"
        icon="Plus"
        @click="batchUserAddDialog = true"
        >批量增加</el-button
      >
      <el-button type="danger" class="batch-delete-button" icon="Minus"
        >批量删除</el-button
      >
      <div class="search-input">
        <el-input
          v-model="search"
          placeholder="请输入搜索内容"
          clearable
          prefix-icon="Search"
          class="search-input-inner"
        ></el-input>
        <el-button
          class="search-button"
          type="primary"
          icon="Search"
          @click="findUserByKeyWord()"
          >搜索</el-button
        >
      </div>
    </div>
    <el-table border class="user-table" :data="userList" :table-layout="auto">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        prop="userId"
        label="用户ID"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="userName"
        label="用户名"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        align="center"
      ></el-table-column>
      <el-table-column prop="sex" label="性别" align="center"></el-table-column>
      <el-table-column
        prop="isLocked"
        label="是否锁定"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="isActived"
        label="是否使用"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="passwordUpdatedTime"
        label="密码最后修改时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="registTime"
        label="注册时间"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <div class="operation-button">
          <el-button type="primary" icon="Edit" plain>编辑</el-button>
          <el-button type="danger" icon="Delete" plain>删除</el-button>
        </div>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="total,prev, pager, next"
      :total="pageTotalCount"
      :page-size="pageSize"
      v-model:current-page="currentPage"
      @current-change="handleCurrentChange"
      lang="zh-CN"
      class="pagination-box"
      v-if="search === null || search === ''"
    ></el-pagination>
  </div>
  <el-dialog
    v-model="userAddDialog"
    title="新增员工"
    width="500px"
    destroy-on-close
    append-to-body
  >
    <el-form
      label-width="120px"
      class="user-add-form"
      :model="user"
      :rules="userRule"
      ref="userRule"
      @submit.prevent="
        (event) => {
          event.preventDefault();
        }
      "
    >
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="user.userName"
          placeholder="请输入用户名"
          clearable
          autocomplete="on"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          show-password
          type="password"
          v-model="user.password"
          clearable
          autocomplete="on"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="重复输入密码" prop="repeatPassword">
        <el-input
          show-password
          type="password"
          v-model="user.repeatPassword"
          clearable
          autocomplete="off"
          placeholder="请再次输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input
          v-model="user.name"
          placeholder="请输入姓名"
          prop="name"
          clearable
          autocomplete="on"
        ></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="user.sex" placeholder="请选择性别" clearable>
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="2"></el-option>
          <el-option label="未知" value="0"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" icon="Plus" @click="addUser()"
          >新增</el-button
        >
        <el-button type="danger" icon="Close" @click="cancel()">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="batchUserAddDialog"
    title="批量增加员工"
    width="1500px"
    destroy-on-close
    append-to-body
  >
    <div class="batch-model-download">
      <el-button type="primary" icon="Download" @click="downloadModel()">
        下载模板</el-button
      >
      <el-upload
        action=""
        v-model:file-list="modelFileList"
        accept=".xlsx, .xls"
        :multiple="false"
        :show-file-list="false"
        :auto-upload="false"
        :limit="1"
        :on-change="uploadModel"
      >
        <el-button type="primary" icon="Upload" style="margin-left: 10px">
          上传模板
        </el-button>
      </el-upload>
    </div>
    <el-table
      border
      class="batch-add-table"
      :data="batchUserList"
      :row-class-name="isSuccessReturn"
    >
      <el-table-column
        prop="userName"
        label="用户名"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        align="center"
      ></el-table-column>
      <el-table-column prop="sex" label="性别" align="center"></el-table-column>
      <el-table-column
        prop="password"
        label="密码"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="isSuccess"
        label="添加情况"
        align="center"
        width="auto"
      >
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" icon="Plus" @click="batchAddUser()"
          >新增</el-button
        >
        <el-button type="danger" icon="Close" @click="batchCancel()"
          >取消</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script>
//import { ca } from "element-plus/es/locale";

//import { Search } from "@element-plus/icons-vue/dist/types";
//import { Service } from "@element-plus/icons-vue/dist/types";

//import { Edit, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import * as xlsx from "xlsx";
export default {
  name: "UserList",
  data() {
    return {
      userList: [],
      pageTotalCount: "",
      pageSize: 5,
      currentPage: 1,
      modelFileList: [],
      search: null,
      userAddDialog: false,
      batchUserAddDialog: false,
      user: {
        userName: "",
        password: "",
        repeatPassword: "",
        name: "",
        sex: "",
        isLocked: "0",
        isActived: "1",
      },
      batchUserList: [],
      userRule: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          //校验规则1：必填
          { required: true, message: "请输入密码", trigger: "blur" },
          //校验规则2：长度6-16位

          {
            min: 6,
            message: "密码长度不能小于6位",
            trigger: ["blur", "change"],
          },
          {
            max: 16,
            message: "密码长度不能超过16位",
            trigger: ["blur", "change"],
          },
          //校验规则3：只能包含数字、字母和特殊符号!、@、#、$、%、^、&、*

          {
            pattern: /^[a-zA-Z0-9!@#$%^&*]+$/,
            message:
              "密码存在非法字符，只允许数字、字母和特殊符号!、@、#、$、%、^、&、*",
            trigger: ["blur", "change"],
          },
          //校验规则4：密码不能与用户名相同
          {
            validator: this.passwordSameAsUserName,
            trigger: ["blur", "change"],
          },
          //校验规则5：密码不能存在连续的三个字符——例如123、abc等

          {
            validator: this.passwrodContinuesThreeChar,
            trigger: ["blur", "change"],
          },
        ],
        repeatPassword: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          {
            validator: this.repeatPasswordSameAsPassword,
            trigger: ["blur", "change"],
          },
        ],
        name: [],
        loading: false,
      },
    };
  },
  mounted() {
    this.findAllUser();
    //this.pageTotalCount(this.userList);
  },
  methods: {
    findAllUser() {
      console.log(
        "当前分页大小：",
        this.pageSize,
        "当前页码：",
        this.currentPage
      );
      this.$axios
        .get("/findAllUser", {
          pageSize: this.pageSize,
          currentPage: this.currentPage,
        })
        .then((res) => {
          if (res.code == 200) {
            console.info("res1", res.data);
            this.userList = res.data.records;
            //console.info("records", this.userList);
            this.pageTotalCount = res.data.total;
            // 处理数据，将数字转换成汉字
            this.userList.forEach((item) => {
              //console.info("isLocked:", item.isLocked);
              if (item.isLocked === "1") {
                item.isLocked = "是";
              } else if (item.isLocked === "0") {
                item.isLocked = "否";
              }
              if (item.isActived === "1") {
                item.isActived = "是";
              } else if (item.isActived === "0") {
                item.isActived = "否";
              }
              if (item.sex === 1) {
                item.sex = "男";
              } else if (item.sex === 2) {
                item.sex = "女";
              } else {
                item.sex = "未知";
              }
              if (!item.passwordUpdatedTime) {
                item.passwordUpdatedTime = "未修改";
              } else {
                item.passwordUpdatedTime;
              }
              if (!item.registTime) {
                item.registTime = "未修改";
              } else {
                item.registTime;
              }
              //item.registTime === "null" ? "未注册" : item.registTime;
            });
            // console.info("res2", res.data);
            // console.info("userList", this.userList);
          }
        });
    },
    passwordSameAsUserName(rule, value, callback) {
      if (!value) {
        return callback();
      } else if (value === this.user.userName) {
        callback(new Error("密码不能与用户名相同"));
      } else {
        callback();
      }
    },
    passwrodContinuesThreeChar(rule, value, callback) {
      //定义正则表达式，匹配连续三个字符：例如abc、123等
      /*const regex = /(\d{3})|([a-zA-Z]{3})/*/ //const regex = (.)\1\1;
      //const regex = /^\w{3}/;
      //const charCode = value.charCodeAt(0);
      if (!value) {
        return callback();
      } else {
        for (let i = 0; i < value.length - 2; i++) {
          //抽取当前字符和下两个字符

          const charCode = value.charCodeAt(i);
          //console.log("第一个字符", charCode);
          const nextCharCode = value.charCodeAt(i + 1);
          //console.log("第二个字符", nextCharCode);
          const thirdCharCode = value.charCodeAt(i + 2);
          //console.log("第三个字符", thirdCharCode);
          if (
            nextCharCode === charCode + 1 ||
            thirdCharCode === nextCharCode + 1
          ) {
            return callback(new Error("密码不能存在连续的三个字符"));
          } else {
            callback();
          }
        }
      }
      // if (regex.test(value)) {
      //   callback(new Error("密码不能存在相同的三个字符"));
      // }
    },
    repeatPasswordSameAsPassword(rule, value, callback) {
      if (!value) {
        return callback();
      } else if (value === this.user.password) {
        callback();
      } else {
        callback(new Error("两次输入的密码不一致"));
      }
    },
    addUser: async function () {
      console.log("触发addUser");

      try {
        console.log("开始验证表单");
        const valid = await this.$refs.userRule.validate();
        console.log("valid:", valid);
        if (valid) {
          this.loading = true;
          this.user.sex = Number(this.user.sex);
          this.$axios.post("/addUser", this.user).then((res) => {
            this.loading = false;
            if (res.code === 200) {
              this.$message.success("添加成功");
              this.findAllUser(); //刷新用户列表
              this.userAddDialog = false;
            } else {
              this.$message.error("添加失败");
            }
          });
        } else {
          confirm("表单验证失败，请检查输入内容是否符合要求");
        }
      } catch (e) {
        console.log("存在异常");
        console.log(e);
      } finally {
        this.loading = false;
      }
    },
    cancel: function () {
      this.userAddDialog = false;
      this.user = {};
    },
    batchCancel: function () {
      this.batchUserAddDialog = false;
      this.findAllUser(); //刷新用户列表

      this.batchUserList = [];
    },
    downloadModel: function () {
      const a = document.createElement("a");
      a.href = "/static/excel/model.xlsx";
      document.body.appendChild(a);
      a.download;
      a.click();
      document.body.removeChild(a);
    },
    uploadModel: function (ev) {
      console.log("触发上传文件");
      let file = ev.raw;
      if (!file) {
        console.log("文件不存在");
        return;
      }
      let reader = new FileReader();
      reader.readAsArrayBuffer(file);
      console.log("reader:", reader);
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        let workbook = xlsx.read(data, { type: "array" });
        console.log(workbook);
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = xlsx.utils.sheet_to_json(firstSheet, { header: 0 });
        console.log(jsonData);
        let keyMap = {
          用户名: "userName",
          姓名: "name",
          密码: "password",
          性别: "sex",
        };
        jsonData.forEach((item) => {
          let obj = {};
          for (let key in item) {
            if (item.hasOwnProperty(key)) {
              const newKey = keyMap[key] || key;
              obj[newKey] = item[key];
            }
          }
          this.batchUserList.push(obj);
        });
        this.batchUserList.forEach((item) => {
          if (item.sex === 1) {
            item.sex = "男";
          } else if (item.sex === 2) {
            item.sex = "女";
          } else {
            item.sex = "未知";
          }
          item["isSuccess"] = "";
        });
        console.log("batchUserList:", this.batchUserList);
      };

      //读取文件内容

      //readAsArrayBuffer(file);
      //console.log(reader);
      //let workbook = xlsx.read(reader.result, { type: "binary" });
      //console.log(workbook);
    },
    //批量添加用户（要实时返回添加情况）
    batchAddUser: function () {
      this.loading = true;
      for (let i = 0; i < this.batchUserList.length; i++) {
        //性别转换会数字形式，1为男，2为女，3为未知
        if (this.batchUserList[i].sex === "男") {
          this.batchUserList[i].sex = 1;
        } else if (this.batchUserList[i].sex === "女") {
          this.batchUserList[i].sex = 2;
        } else {
          this.batchUserList[i].sex = 3;
        }
        this.$axios.post("/loopAddUser", this.batchUserList[i]).then((res) => {
          if (res.code === 200) {
            if ((res.data = true)) {
              this.batchUserList[i].isSuccess = "成功";
            } else {
              this.batchUserList[i].isSuccess = "失败";
            }
          } else {
            this.batchUserList[i].isSuccess = "失败";
          }
        });
      }
      this.loading = false;
    },
    isSuccessReturn: function ({ row, rowindex, rowkey }) {
      if (row.isSuccess === "失败") {
        return "orange-bg";
      }
      return "";
    },
    totalCount(userList) {
      //confirm("总数为：" + userList.length);
      return userList.length;
    },
    //分页页码改变时触发方法
    handleCurrentChange(val) {
      alert("当前页：" + val);
      this.currentPage = val;
      this.findAllUser(); //刷新用户列表
    },
    findUserByKeyWord: async function () {
      if (this.search === null) {
        ElMessage.info("请输入关键字");
        return;
      } else {
        this.$axios.post("/findUserByKeyWord", this.search).then((res) => {
          if (res.code === 200) {
            this.userList = res.data.records;
          } else {
            ElMessage.error("查询失败");
          }
        });
      }
    },
  },
};
</script>

<style>
@import url("../../assets/css/reset.css");
.user-list-page {
  width: 100%;
  height: 100%;

  /* background: deeppink; */
}
.user-table {
  width: 100%;
  height: 100%;
  margin-top: 20px;
}
.handle-box {
  width: 100%;
  height: 40px;
}
.add-user-button {
  float: left;
  margin-left: 20px;
}
.batch-delete-button {
  /* float: left; */
  margin-left: 20px;
}
.search-input {
  display: flex;
  float: right;
  margin-right: 20px;
  width: 300px;
}
.search-input-inner {
  width: 200px;
}
.search-button {
  margin-left: 10px;
}
.user-add-form {
  max-width: 600px;

  justify-content: center; /* 水平居中 */
  align-items: center;
}
.batch-model-download {
  /*display: block;*/
  display: flex;
  width: 100%;
}
.batch-add-table {
  width: 100%;
  height: 100%;
  margin-top: 10px;
}
.el-table .orange-bg {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.pagination-box {
  display: flex;
  justify-content: right; /* 水平居右 */
  margin-top: 20px;
  margin-right: 20px;
}
</style>